package com.gemcoder.system.service;

import static com.gemcoder.system.datasource.JdbcTemplateUtil.executeSQL;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import static com.gemcoder.system.service.UserSdkService.sdkOfGetCurrentUserName;
import static com.gemcoder.system.service.UserSdkService.sdkOfGetCurrentUserId;
import com.gemcoder.system.bo.Result;
import static com.gemcoder.system.service.permission.PermissionSdkService.sdkOfgetAllPermissions;
import static com.gemcoder.system.service.permission.PermissionSdkService.sdkOfgetAllMenus;
import java.sql.SQLException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.map.MapUtil;

@Service
public class UsermanagementService {

    public Result queryUsers(Map<String, Object> paramMap) {
        String accountNumber = paramMap.get("accountNumber") != null ? String.valueOf(paramMap.get("accountNumber")) : null;
        Integer current = paramMap.get("current") != null ? Integer.valueOf(String.valueOf(paramMap.get("current"))) : 1;
        Integer pageSize = paramMap.get("pageSize") != null ? Integer.valueOf(String.valueOf(paramMap.get("pageSize"))) : 10;
        StringBuilder sql = new StringBuilder("SELECT id, user_name, email, phone_number, phone, status FROM users WHERE 1=1");
        List<Object> params = new ArrayList<>();
        if (accountNumber != null) {
            sql.append(" AND user_name = ?");
            params.add(accountNumber);
        }
        sql.append(" LIMIT ?, ?");
        params.add((current - 1) * pageSize);
        params.add(pageSize);
        List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());
        StringBuilder countSql = new StringBuilder("SELECT COUNT(*) as total FROM users WHERE 1=1");
        List<Object> countParams = new ArrayList<>();
        if (accountNumber != null) {
            countSql.append(" AND user_name = ?");
            countParams.add(accountNumber);
        }
        List<Map<String, Object>> countResult = executeSQL(countSql.toString(), countParams.toArray());
        int total = Integer.valueOf(String.valueOf(countResult.get(0).get("total")));
        Result result = new Result();
        result.setFlag(true);
        result.setData(Map.of("total", total, "data", data));
        return result;
    }

    public Result resetUsers(Map<String, Object> paramMap) {
        StringBuilder sql = new StringBuilder("SELECT id, user_name, email, phone_number, phone, status FROM users LIMIT ?, ?");
        List<Object> params = new ArrayList<>();
        Integer current = paramMap.get("current") != null ? Integer.valueOf(String.valueOf(paramMap.get("current"))) : 1;
        Integer pageSize = paramMap.get("pageSize") != null ? Integer.valueOf(String.valueOf(paramMap.get("pageSize"))) : 10;
        params.add((current - 1) * pageSize);
        params.add(pageSize);
        List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());
        StringBuilder countSql = new StringBuilder("SELECT COUNT(*) as total FROM users");
        List<Map<String, Object>> countResult = executeSQL(countSql.toString());
        int total = Integer.valueOf(String.valueOf(countResult.get(0).get("total")));
        Result result = new Result();
        result.setFlag(true);
        result.setData(Map.of("total", total, "data", data));
        return result;
    }

    public Result addUser(Map<String, Object> paramMap) {
        String userName = paramMap.get("userName") != null ? String.valueOf(paramMap.get("userName")) : null;
        String password = paramMap.get("password") != null ? String.valueOf(paramMap.get("password")) : null;
        String nickName = paramMap.get("nickName") != null ? String.valueOf(paramMap.get("nickName")) : null;
        String email = paramMap.get("email") != null ? String.valueOf(paramMap.get("email")) : null;
        String phoneNumber = paramMap.get("phoneNumber") != null ? String.valueOf(paramMap.get("phoneNumber")) : null;
        String phone = paramMap.get("phone") != null ? String.valueOf(paramMap.get("phone")) : null;
        // 默认值
        String status = "0";
        org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder encoder = new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(password);
        StringBuilder sql = new StringBuilder("INSERT INTO users (user_name, password, nick_name, email, phone_number, phone, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
        List<Object> params = new ArrayList<>();
        params.add(userName);
        params.add(encodedPassword);
        params.add(nickName);
        params.add(email);
        params.add(phoneNumber);
        params.add(phone);
        params.add(status);
        int insertRows = executeSQL(sql.toString(), params.toArray());
        Result result = new Result();
        result.setFlag(insertRows > 0);
        return result;
    }

    public Result refreshUsers(Map<String, Object> paramMap) {
        return resetUsers(paramMap);
    }

    public Result initUsers(Map<String, Object> paramMap) {
        return resetUsers(paramMap);
    }

    public Result paginateUsers(Map<String, Object> paramMap) {
        return queryUsers(paramMap);
    }

    public Result updateUser(Map<String, Object> paramMap) {
        Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        String userName = paramMap.get("userName") != null ? String.valueOf(paramMap.get("userName")) : null;
        String nickName = paramMap.get("nickName") != null ? String.valueOf(String.valueOf(paramMap.get("nickName"))) : null;
        String email = paramMap.get("email") != null ? String.valueOf(paramMap.get("email")) : null;
        String phoneNumber = paramMap.get("phoneNumber") != null ? String.valueOf(paramMap.get("phoneNumber")) : null;
        String phone = paramMap.get("phone") != null ? String.valueOf(paramMap.get("phone")) : null;
        String status = paramMap.get("status") != null ? String.valueOf(paramMap.get("status")) : null;
        StringBuilder sql = new StringBuilder("UPDATE users SET user_name = ?, nick_name = ?, email = ?, phone_number = ?, phone = ?, status = ? WHERE id = ?");
        List<Object> params = new ArrayList<>();
        params.add(userName);
        params.add(nickName);
        params.add(email);
        params.add(phoneNumber);
        params.add(phone);
        params.add(status);
        params.add(id);
        int updateRows = executeSQL(sql.toString(), params.toArray());
        Result result = new Result();
        result.setFlag(updateRows > 0);
        return result;
    }

    public Result getUserDetails(Map<String, Object> paramMap) {
        Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        StringBuilder sql = new StringBuilder("SELECT id, user_name, email, phone_number, phone, status FROM users WHERE id = ?");
        List<Object> params = new ArrayList<>();
        params.add(id);
        List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());
        Result result = new Result();
        result.setFlag(true);
        result.setData(data.isEmpty() ? null : data.get(0));
        return result;
    }

    public Result updateUserRole(Map<String, Object> paramMap) {
        Integer userId = paramMap.get("userId") != null ? Integer.valueOf(String.valueOf(paramMap.get("userId"))) : null;
        Integer roleId = paramMap.get("roleId") != null ? Integer.valueOf(String.valueOf(paramMap.get("roleId"))) : null;
        StringBuilder sql = new StringBuilder("UPDATE user_role SET role_id = ? WHERE user_id = ?");
        List<Object> params = new ArrayList<>();
        params.add(roleId);
        params.add(userId);
        int updateRows = executeSQL(sql.toString(), params.toArray());
        Result result = new Result();
        result.setFlag(updateRows > 0);
        return result;
    }

    public Result resetUserPassword(Map<String, Object> paramMap) {
        Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        String newPassword = paramMap.get("newPassword") != null ? String.valueOf(paramMap.get("newPassword")) : null;
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(newPassword);
        StringBuilder sql = new StringBuilder("UPDATE users SET password = ? WHERE id = ?");
        List<Object> params = new ArrayList<>();
        params.add(encodedPassword);
        params.add(id);
        int updateRows = executeSQL(sql.toString(), params.toArray());
        Result result = new Result();
        result.setFlag(updateRows > 0);
        return result;
    }

    public Result deleteUser(Map<String, Object> paramMap) {
        Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        StringBuilder sql = new StringBuilder("DELETE FROM users WHERE id = ?");
        List<Object> params = new ArrayList<>();
        params.add(id);
        int deleteRows = executeSQL(sql.toString(), params.toArray());
        Result result = new Result();
        result.setFlag(deleteRows > 0);
        return result;
    }

    public Result getAllRoles(Map<String, Object> paramMap) {
        // 构建查询所有角色的SQL
        StringBuilder sql = new StringBuilder("SELECT id, role_name, role_code, role_description FROM role");
        List<Map<String, Object>> roles = executeSQL(sql.toString());
        // 返回结果
        Result result = new Result();
        result.setFlag(true);
        result.setMessage("查询成功");
        result.setData(roles);
        return result;
    }

    public Result getUserRoles(Map<String, Object> paramMap) {
        // 获取用户ID
        Integer userId = paramMap.get("userId") != null ? Integer.valueOf(String.valueOf(paramMap.get("userId"))) : null;
        if (userId == null) {
            Result result = new Result();
            result.setFlag(false);
            result.setMessage("用户ID不能为空");
            return result;
        }
        // 构建查询用户角色的SQL
        StringBuilder sql = new StringBuilder("SELECT r.id, r.role_name, r.role_code, r.role_description ");
        sql.append("FROM role r ");
        sql.append("JOIN user_role ur ON r.id = ur.role_id ");
        sql.append("WHERE ur.user_id = ?");
        List<Map<String, Object>> userRoles = executeSQL(sql.toString(), userId);
        // 返回结果
        Result result = new Result();
        result.setFlag(true);
        result.setMessage("查询成功");
        result.setData(userRoles);
        return result;
    }

    public Result toggleUserStatus(Map<String, Object> paramMap) {
        // 获取用户ID
        Integer userId = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        if (userId == null) {
            return new Result(false, "用户ID不能为空", null);
        }
        // 查询当前用户状态
        StringBuilder querySql = new StringBuilder("SELECT status FROM users WHERE id = ?");
        List<Map<String, Object>> queryResult = executeSQL(querySql.toString(), userId);
        if (queryResult == null || queryResult.isEmpty()) {
            return new Result(false, "用户不存在", null);
        }
        // 获取当前状态
        Integer currentStatus = Integer.valueOf(String.valueOf(queryResult.get(0).get("status")));
        // 如果当前状态是锁定(2)，则更新为启用(0)，否则更新为锁定(2)
        Integer newStatus = (currentStatus == 2) ? 0 : 2;
        // 更新用户状态
        StringBuilder updateSql = new StringBuilder("UPDATE users SET status = ? WHERE id = ?");
        int updateResult = executeSQL(updateSql.toString(), newStatus, userId);
        if (updateResult > 0) {
            return new Result(true, "用户状态更新成功", null);
        } else {
            return new Result(false, "用户状态更新失败", null);
        }
    }
}
